package day_2022_12_to_3.year2023;

import java.util.HashMap;
import java.util.Map;

/**
 * @author haomin
 * @date 2023/02/13 23:57
 **/
public class Day2_13_Num1234 {class Solution {
    public int balancedString(String s) {

        Map<Character, Integer> map = new HashMap<Character, Integer>(4) {{
            put('Q', 0);
            put('W', 1);
            put('E', 2);
            put('R', 3);
        }};

        int[] counts = new int[4];
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            counts[map.get(chars[i])]++;
        }

        int average = chars.length / 4;
        if (counts[0] == average && counts[1] == average && counts[2] == average && counts[3] == average) {
            return 0;
        }

        int minLength = chars.length;
        for (int left = 0, right = 0; right < chars.length; right++) {

            counts[map.get(chars[right])]--;

            outer:
            while (left <= right) {
                for (int i = 0; i < counts.length; i++) {
                    if (counts[i] > average) {
                        break outer;
                    }
                }
                minLength = Math.min(minLength, right - left + 1);
                counts[map.get(chars[left++])]++;
            }

        }

        return minLength;

    }
}
}